package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.*;
import connection.ServiceProxy;

/**
 * Servlet implementation class ViewPurchasedItem
 */
public class ViewPurchasedItem extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewPurchasedItem() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		this.getPurchasedItems(request,response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.getPurchasedItems(request,response);
	}
	
	private void getPurchasedItems(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String result = null, message = null;
		HttpSession session = request.getSession();
		String userId = (String)session.getAttribute("userId");
		
		ServiceProxy oProxy = new ServiceProxy();
		TransactedItem aoTransactedItem[] = oProxy.getPurchasedItems(userId);
		if(null == aoTransactedItem) {
			
			message = "No Items Purchased";
			request.setAttribute("message", message);
		}
		else {
		
			request.setAttribute("TransactedItem", aoTransactedItem);
			
			Advertisement aoAdvert[] = oProxy.getOtherAdvertisementExcludingId(userId);
			System.out.println("Length" + aoAdvert.length);
			request.setAttribute("Advertisement", aoAdvert);
		}
		RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/viewPurchasedItem.jsp");
		rd.forward(request, response);
	}

}
